package tk.jfree.example.solr.api.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.mapping.SolrDocument;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.HighlightOptions;
import org.springframework.data.solr.core.query.SimpleFacetAndHighlightQuery;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Repository;
import tk.jfree.example.solr.api.pagehelper.Page;
import tk.jfree.example.solr.model.Article;
import tk.jfree.example.solr.model.Query;


import java.util.Optional;

/**
 * @author Cheng.Wei
 * @date 2019/04/29 00:36
 */
@Repository
public class ArticleRepositoryImpl implements ArticleQueryRepository {


    @Autowired private SolrTemplate solrTemplate;

    @Override
    public Page query(Query query) {
        query = Optional.ofNullable(query).orElseGet(Query::new);
        Criteria criteria = new Criteria("tc").is(query.getKeyWord());
        SimpleFacetAndHighlightQuery simpleFacetAndHighlightQuery = new SimpleFacetAndHighlightQuery(criteria, PageRequest.of(Optional.ofNullable(query.getPageNum()).orElse(1)-1,
                Optional.ofNullable(query.getPageSize()).orElse(20)));
        // 设置高亮显示的域
        HighlightOptions highlightOptions = new HighlightOptions().addField("title", "author","content");
        // 设置高亮前缀/后缀
        highlightOptions.setSimplePrefix("<em style='color:red'>").setSimplePostfix("</em>");
        simpleFacetAndHighlightQuery.setHighlightOptions(highlightOptions);

        HighlightPage<Article> highlightPage = solrTemplate.queryForHighlightPage(Article.class.getAnnotation(SolrDocument.class).collection(), simpleFacetAndHighlightQuery, Article.class);
        Page page = Page.builder()
                .total(highlightPage.getTotalElements())
                .pages(highlightPage.getTotalPages())
                .pageNum(query.getPageNum())
                .pageSize(query.getPageSize())
                .list(highlightPage.getHighlighted())
                .build();
        return page;
    }
}
